<template>
    <div class="HeaderCellSort" @click="handleClick">
        <span>{{ label }}</span>
        <span class="caret-wrapper">
            <i
                class="sort-caret ascending"
                :class="{active: ascActive}"
                @click.stop="handleSortChange('asc')"
            ></i>
            <i
                class="sort-caret descending"
                :class="{active: descActive}"
                @click.stop="handleSortChange('desc')"
            ></i>
        </span>
    </div>
</template>

<script>
export default {
  name: 'HeaderCellSort',
  props: {
    // 列索引值
    index: {
      type: Number,
    },
    // 列字段
    prop: {
      type: String,
    },
    // 列名
    label: {
      type: String,
    },
    // 列定义
    column: {
      type: Object,
    },
    // 排序
    sort: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  computed: {
    ascActive() {
      return this.sort.prop === this.prop && this.sort.order === 'asc'
    },
    descActive() {
      return this.sort.prop === this.prop && this.sort.order === 'desc'
    },
  },
  methods: {
    handleSortChange(order) {
      this.sort.prop = this.prop
      this.sort.order = order
      this.$emit('sort-change', this.prop, order)
    },
    handleClick() {
      let order = ''
      if (this.ascActive) {
        order = 'desc'
      } else if (this.descActive) {
        order = ''
      } else {
        order = 'asc'
      }
      this.handleSortChange(order)
    },
  },
}
</script>
